package com.ruoyi.project.system.mobile.api;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.file.domain.File;
import com.ruoyi.project.system.file.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Controller
@RequestMapping("/mobile")
public class MobileController extends BaseController {

    @Autowired
    private IFileService fileService;

    //文件上传
    @RequestMapping("/uploadFile")
    @ResponseBody
    public AjaxResult uploadFile(@RequestParam("files") MultipartFile[] file, @RequestParam("id") String id){
        String filePath= RuoYiConfig.getUploadPath();
        if (file==null){
            return AjaxResult.error("文件不能为空！");
        }

        try {
            for (int i=0;i< file.length;i++){
                String filePath1= FileUploadUtils.upload(filePath,file[i]);
                File file1=new File();
                file1.setFileName(file[i].getOriginalFilename());

                file1.setFileAddress(Constants.FILE_PATH_PREFIX+filePath1.split(Constants.RESOURCE_PREFIX)[1].split(StringUtils.substring(RuoYiConfig.getUploadPath(),RuoYiConfig.getProfile().length()+1))[1]);

                file1.setId(Long.parseLong(id));
                fileService.updateFile(file1);
            }
        }catch (IOException e){
            e.printStackTrace();
            AjaxResult.error("上传文件失败！");
        }
        return AjaxResult.success("文件上传成功!");
    }
}
